-- Lua Battle System - 性能监控和自动调优系统
-- 提供实时性能监控、异常检测和自动调优功能

local Logger = require("utils.logger")
local TableUtils = require("utils.table_utils")

local PerformanceMonitor = {
    -- 监控配置
    config = {
        -- 监控间隔
        monitoring_interval = 1, -- 秒

        -- 性能阈值
        performance_thresholds = {
            response_time = { warning = 100, critical = 200 }, -- 毫秒
            memory_usage = { warning = 80, critical = 95 }, -- 百分比
            cpu_usage = { warning = 70, critical = 90 }, -- 百分比
            error_rate = { warning = 0.05, critical = 0.1 }, -- 错误率
            fps = { warning = 45, critical = 30 } -- 帧率
        },

        -- 自动调优配置
        auto_tuning = {
            enabled = true,
            aggressive_mode = false, -- 激进调优模式
            tuning_cooldown = 30, -- 调优冷却时间（秒）
            max_consecutive_tunings = 3, -- 最大连续调优次数
            rollback_on_failure = true -- 失败时回滚
        },

        -- 告警配置
        alerting = {
            enabled = true,
            alert_cooldown = 60, -- 告警冷却时间（秒）
            persistent_alerts = true, -- 持续告警
            alert_channels = {"console", "file", "callback"}
        },

        -- 数据保留配置
        data_retention = {
            real_time_window = 60, -- 实时数据窗口（秒）
            history_window = 3600, -- 历史数据窗口（秒）
            max_history_points = 1000 -- 最大历史数据点数
        }
    },

    -- 当前状态
    state = {
        is_monitoring = false,
        start_time = 0,
        last_monitoring_time = 0,
        current_performance = {},
        performance_history = {},
        alerts = {},
        tuning_history = {},
        system_resources = {},
        health_score = 1.0
    },

    -- 性能指标收集器
    collectors = {},

    -- 调优策略
    tuning_strategies = {}
}

-- 初始化性能监控器
function PerformanceMonitor:init(config)
    Logger.info("初始化性能监控系统")

    -- 合并配置
    if config then
        TableUtils.merge(self.config, config)
    end

    -- 初始化收集器
    self:init_collectors()

    -- 初始化调优策略
    self:init_tuning_strategies()

    -- 初始化性能数据结构
    self.state.start_time = os.time()
    self.state.current_performance = self:initialize_performance_metrics()

    Logger.info("性能监控系统初始化完成", {
        monitoring_interval = self.config.monitoring_interval,
        auto_tuning_enabled = self.config.auto_tuning.enabled
    })
end

-- 初始化性能指标
function PerformanceMonitor:initialize_performance_metrics()
    return {
        response_time = {
            current = 0,
            average = 0,
            min = math.huge,
            max = 0,
            samples = 0,
            trend = "stable"
        },
        memory_usage = {
            current = 0,
            average = 0,
            peak = 0,
            trend = "stable"
        },
        cpu_usage = {
            current = 0,
            average = 0,
            peak = 0,
            trend = "stable"
        },
        error_rate = {
            current = 0,
            total_errors = 0,
            total_operations = 0,
            trend = "stable"
        },
        fps = {
            current = 0,
            average = 0,
            min = math.huge,
            max = 0,
            trend = "stable"
        },
        ai_performance = {
            decision_time = 0,
            decision_quality = 0,
            tuning_frequency = 0,
            trend = "stable"
        }
    }
end

-- 初始化数据收集器
function PerformanceMonitor:init_collectors()
    self.collectors = {
        response_time = self:response_time_collector(),
        memory_usage = self:memory_usage_collector(),
        cpu_usage = self:cpu_usage_collector(),
        error_rate = self:error_rate_collector(),
        fps = self:fps_collector(),
        ai_performance = self:ai_performance_collector()
    }
end

-- 响应时间收集器
function PerformanceMonitor:response_time_collector()
    local start_time

    return {
        start = function()
            start_time = os.clock()
        end,

        stop = function()
            if start_time then
                local elapsed = (os.clock() - start_time) * 1000 -- 转换为毫秒
                start_time = nil
                return elapsed
            end
            return 0
        end,

        measure = function(operation)
            local start = os.clock()
            local result = operation()
            local elapsed = (os.clock() - start) * 1000
            return result, elapsed
        end
    }
end

-- 内存使用收集器
function PerformanceMonitor:memory_usage_collector()
    return {
        get_current = function()
            -- 使用collectgarbage获取内存信息
            local kb = collectgarbage("count")
            return kb -- KB
        end,

        get_peak = function()
            return collectgarbage("count")
        end,

        force_gc = function()
            collectgarbage("collect")
        end
    }
end

-- CPU使用率收集器
function PerformanceMonitor:cpu_usage_collector()
    local last_cpu_time = 0
    local last_check_time = 0

    return {
        get_current = function()
            local current_time = os.time()

            -- 简化的CPU使用率计算
            -- 实际实现可能需要使用系统特定API
            if current_time > last_check_time then
                local time_diff = current_time - last_check_time
                if time_diff > 0 then
                    -- 模拟CPU使用率
                    local cpu_usage = math.random(10, 80)
                    last_cpu_time = cpu_usage
                    last_check_time = current_time
                    return cpu_usage
                end
            end

            return last_cpu_time
        end,

        reset = function()
            last_cpu_time = 0
            last_check_time = 0
        end
    }
end

-- 错误率收集器
function PerformanceMonitor:error_rate_collector()
    local error_count = 0
    local operation_count = 0

    return {
        record_error = function()
            error_count = error_count + 1
        end,

        record_operation = function()
            operation_count = operation_count + 1
        end,

        get_rate = function()
            if operation_count == 0 then
                return 0
            end
            return error_count / operation_count
        end,

        reset = function()
            error_count = 0
            operation_count = 0
        end,

        get_stats = function()
            return {
                error_count = error_count,
                operation_count = operation_count,
                error_rate = operation_count > 0 and (error_count / operation_count) or 0
            }
        end
    }
end

-- 帧率收集器
function PerformanceMonitor:fps_collector()
    local frame_count = 0
    local last_fps_time = 0
    local current_fps = 0

    return {
        record_frame = function()
            frame_count = frame_count + 1
        end,

        calculate_fps = function()
            local current_time = os.time()
            if current_time > last_fps_time then
                local time_diff = current_time - last_fps_time
                if time_diff > 0 then
                    current_fps = frame_count / time_diff
                    frame_count = 0
                    last_fps_time = current_time
                    return current_fps
                end
            end
            return current_fps
        end,

        get_current = function()
            local current_time = os.time()
            if current_time > last_fps_time then
                local time_diff = current_time - last_fps_time
                if time_diff > 0 then
                    current_fps = frame_count / time_diff
                    frame_count = 0
                    last_fps_time = current_time
                    return current_fps
                end
            end
            return current_fps
        end,

        reset = function()
            frame_count = 0
            last_fps_time = os.time()
            current_fps = 0
        end
    }
end

-- AI性能收集器
function PerformanceMonitor:ai_performance_collector()
    local ai_metrics = {
        decision_times = {},
        decision_qualities = {},
        tuning_count = 0
    }

    return {
        record_decision = function(decision_time, decision_quality)
            table.insert(ai_metrics.decision_times, decision_time)
            table.insert(ai_metrics.decision_qualities, decision_quality)

            -- 限制历史记录数量
            if #ai_metrics.decision_times > 100 then
                table.remove(ai_metrics.decision_times, 1)
                table.remove(ai_metrics.decision_qualities, 1)
            end
        end,

        record_tuning = function()
            ai_metrics.tuning_count = ai_metrics.tuning_count + 1
        end,

        get_average_decision_time = function()
            if #ai_metrics.decision_times == 0 then
                return 0
            end

            local total = 0
            for _, time in ipairs(ai_metrics.decision_times) do
                total = total + time
            end
            return total / #ai_metrics.decision_times
        end,

        get_average_decision_quality = function()
            if #ai_metrics.decision_qualities == 0 then
                return 0
            end

            local total = 0
            for _, quality in ipairs(ai_metrics.decision_qualities) do
                total = total + quality
            end
            return total / #ai_metrics.decision_qualities
        end,

        get_metrics = function()
            return {
                avg_decision_time = get_average_decision_time(),
                avg_decision_quality = get_average_decision_quality(),
                tuning_count = ai_metrics.tuning_count,
                decision_count = #ai_metrics.decision_times
            }
        end,

        reset = function()
            ai_metrics.decision_times = {}
            ai_metrics.decision_qualities = {}
            ai_metrics.tuning_count = 0
        end
    }
end

-- 初始化调优策略
function PerformanceMonitor:init_tuning_strategies()
    self.tuning_strategies = {
        memory_optimization = self:memory_optimization_strategy(),
        performance_balancing = self:performance_balancing_strategy(),
        ai_parameter_adjustment = self:ai_parameter_adjustment_strategy(),
        garbage_collection_tuning = self:garbage_collection_tuning_strategy()
    }
end

-- 内存优化策略
function PerformanceMonitor:memory_optimization_strategy()
    return {
        name = "memory_optimization",
        priority = 1,

        should_trigger = function(performance_data)
            return performance_data.memory_usage.current > self.config.performance_thresholds.memory_usage.warning
        end,

        execute = function(performance_data)
            Logger.info("执行内存优化策略")

            -- 强制垃圾回收
            self.collectors.memory_usage.force_gc()

            -- 降低缓存大小
            if performance_data.memory_usage.current > self.config.performance_thresholds.memory_usage.critical then
                self:reduce_caches()
            end

            return {success = true, message = "内存优化完成"}
        end,

        rollback = function()
            Logger.info("回滚内存优化策略")
            -- 恢复缓存设置
            self:restore_caches()
        end
    }
end

-- 性能平衡策略
function PerformanceMonitor:performance_balancing_strategy()
    return {
        name = "performance_balancing",
        priority = 2,

        should_trigger = function(performance_data)
            return performance_data.response_time.current > self.config.performance_thresholds.response_time.warning
        end,

        execute = function(performance_data)
            Logger.info("执行性能平衡策略")

            -- 调整AI决策时间限制
            if performance_data.ai_performance.decision_time > 50 then
                self:adjust_ai_time_limit(0.8) -- 减少20%
            end

            -- 优化更新频率
            if performance_data.fps.current < self.config.performance_thresholds.fps.warning then
                self:adjust_update_frequency(0.9) -- 减少10%
            end

            return {success = true, message = "性能平衡调整完成"}
        end,

        rollback = function()
            Logger.info("回滚性能平衡策略")
            self:restore_ai_time_limit()
            self:restore_update_frequency()
        end
    }
end

-- AI参数调整策略
function PerformanceMonitor:ai_parameter_adjustment_strategy()
    return {
        name = "ai_parameter_adjustment",
        priority = 3,

        should_trigger = function(performance_data)
            return performance_data.ai_performance.decision_quality < 0.6
        end,

        execute = function(performance_data)
            Logger.info("执行AI参数调整策略")

            -- 通知AI参数调优器进行调整
            if self.ai_parameter_tuner then
                self.ai_parameter_tuner:force_tuning()
            end

            return {success = true, message = "AI参数调整触发"}
        end,

        rollback = function()
            Logger.info("回滚AI参数调整策略")
            -- 由AI参数调优器处理回滚
        end
    }
end

-- 垃圾回收调优策略
function PerformanceMonitor:garbage_collection_tuning_strategy()
    return {
        name = "garbage_collection_tuning",
        priority = 4,

        should_trigger = function(performance_data)
            return performance_data.memory_usage.current > self.config.performance_thresholds.memory_usage.critical
        end,

        execute = function(performance_data)
            Logger.info("执行垃圾回收调优策略")

            -- 增加GC频率
            collectgarbage("setpause", 100) -- 降低GC暂停阈值
            collectgarbage("setstepmul", 200) -- 增加GC步长倍数

            -- 立即执行GC
            collectgarbage("collect")

            return {success = true, message = "垃圾回收参数调优完成"}
        end,

        rollback = function()
            Logger.info("回滚垃圾回收调优策略")
            collectgarbage("setpause", 200) -- 恢复默认值
            collectgarbage("setstepmul", 200) -- 恢复默认值
        end
    }
end

-- 启动性能监控
function PerformanceMonitor:start_monitoring()
    if self.state.is_monitoring then
        Logger.warn("性能监控已在运行")
        return
    end

    self.state.is_monitoring = true
    self.state.last_monitoring_time = os.time()

    Logger.info("性能监控已启动")

    -- 启动监控循环
    self:monitoring_loop()
end

-- 停止性能监控
function PerformanceMonitor:stop_monitoring()
    self.state.is_monitoring = false
    Logger.info("性能监控已停止")
end

-- 监控循环
function PerformanceMonitor:monitoring_loop()
    if not self.state.is_monitoring then
        return
    end

    local current_time = os.time()

    -- 检查是否到了监控时间
    if current_time - self.state.last_monitoring_time >= self.config.monitoring_interval then
        self:collect_performance_metrics()
        self:analyze_performance()
        self:check_auto_tuning()
        self:update_health_score()

        self.state.last_monitoring_time = current_time
    end

    -- 继续监控循环
    -- 实际实现中可能需要使用定时器或协程
end

-- 收集性能指标
function PerformanceMonitor:collect_performance_metrics()
    local current_time = os.time()

    -- 收集各项指标
    self.state.current_performance.memory_usage.current = self.collectors.memory_usage.get_current()
    self.state.current_performance.cpu_usage.current = self.collectors.cpu_usage.get_current()
    self.state.current_performance.fps.current = self.collectors.fps.get_current()

    local error_stats = self.collectors.error_rate.get_stats()
    self.state.current_performance.error_rate.current = error_stats.error_rate

    local ai_metrics = self.collectors.ai_performance.get_metrics()
    self.state.current_performance.ai_performance.decision_time = ai_metrics.avg_decision_time
    self.state.current_performance.ai_performance.decision_quality = ai_metrics.avg_decision_quality

    -- 更新统计信息
    self:update_performance_statistics()

    -- 添加到历史记录
    self:add_to_history(current_time)
end

-- 更新性能统计信息
function PerformanceMonitor:update_performance_statistics()
    local perf = self.state.current_performance

    -- 更新响应时间统计
    if perf.response_time.samples > 0 then
        perf.response_time.average = (
            (perf.response_time.average * (perf.response_time.samples - 1) + perf.response_time.current) /
            perf.response_time.samples
        )
        perf.response_time.min = math.min(perf.response_time.min, perf.response_time.current)
        perf.response_time.max = math.max(perf.response_time.max, perf.response_time.current)
    end

    -- 更新内存使用统计
    perf.memory_usage.average = (
        perf.memory_usage.average + perf.memory_usage.current
    ) / 2
    perf.memory_usage.peak = math.max(perf.memory_usage.peak, perf.memory_usage.current)

    -- 更新CPU使用统计
    perf.cpu_usage.average = (
        perf.cpu_usage.average + perf.cpu_usage.current
    ) / 2
    perf.cpu_usage.peak = math.max(perf.cpu_usage.peak, perf.cpu_usage.current)

    -- 更新FPS统计
    if perf.fps.samples > 0 then
        perf.fps.average = (
            (perf.fps.average * (perf.fps.samples - 1) + perf.fps.current) /
            perf.fps.samples
        )
        perf.fps.min = math.min(perf.fps.min, perf.fps.current)
        perf.fps.max = math.max(perf.fps.max, perf.fps.current)
    end
end

-- 添加到历史记录
function PerformanceMonitor:add_to_history(timestamp)
    local snapshot = {
        timestamp = timestamp,
        performance = TableUtils.deep_copy(self.state.current_performance)
    }

    table.insert(self.state.performance_history, snapshot)

    -- 限制历史记录数量
    while #self.state.performance_history > self.config.data_retention.max_history_points do
        table.remove(self.state.performance_history, 1)
    end

    -- 清理过期数据
    local cutoff_time = timestamp - self.config.data_retention.history_window
    while #self.state.performance_history > 0 and self.state.performance_history[1].timestamp < cutoff_time do
        table.remove(self.state.performance_history, 1)
    end
end

-- 分析性能
function PerformanceMonitor:analyze_performance()
    local perf = self.state.current_performance

    -- 分析趋势
    self:analyze_trends()

    -- 检查阈值
    self:check_thresholds()

    -- 生成性能报告
    self:generate_performance_report()
end

-- 分析性能趋势
function PerformanceMonitor:analyze_trends()
    local history = self.state.performance_history
    if #history < 5 then
        return
    end

    local recent = {}
    for i = math.max(1, #history - 4), #history do
        table.insert(recent, history[i])
    end

    -- 计算趋势
    local trends = {
        response_time = self:calculate_metric_trend(recent, "response_time.current"),
        memory_usage = self:calculate_metric_trend(recent, "memory_usage.current"),
        cpu_usage = self:calculate_metric_trend(recent, "cpu_usage.current"),
        fps = self:calculate_metric_trend(recent, "fps.current")
    }

    -- 更新趋势信息
    for metric, trend in pairs(trends) do
        if self.state.current_performance[metric] then
            self.state.current_performance[metric].trend = trend
        end
    end
end

-- 计算指标趋势
function PerformanceMonitor:calculate_metric_trend(data_points, metric_path)
    if #data_points < 2 then
        return "stable"
    end

    local values = {}
    for _, point in ipairs(data_points) do
        local value = self:get_nested_value(point, metric_path)
        if value then
            table.insert(values, value)
        end
    end

    if #values < 2 then
        return "stable"
    end

    -- 计算趋势
    local first_half = {}
    local second_half = {}
    local mid_point = math.floor(#values / 2)

    for i = 1, mid_point do
        table.insert(first_half, values[i])
    end

    for i = mid_point + 1, #values do
        table.insert(second_half, values[i])
    end

    local first_avg = self:calculate_average(first_half)
    local second_avg = self:calculate_average(second_half)

    local change_percent = (second_avg - first_avg) / first_avg

    if change_percent > 0.1 then
        return "increasing"
    elseif change_percent < -0.1 then
        return "decreasing"
    else
        return "stable"
    end
end

-- 获取嵌套值
function PerformanceMonitor:get_nested_value(obj, path)
    local keys = {}
    for key in string.gmatch(path, "[^.]+") do
        table.insert(keys, key)
    end

    local value = obj
    for _, key in ipairs(keys) do
        if value and value[key] then
            value = value[key]
        else
            return nil
        end
    end

    return value
end

-- 计算平均值
function PerformanceMonitor:calculate_average(values)
    if #values == 0 then
        return 0
    end

    local sum = 0
    for _, value in ipairs(values) do
        sum = sum + value
    end

    return sum / #values
end

-- 检查性能阈值
function PerformanceMonitor:check_thresholds()
    local perf = self.state.current_performance
    local thresholds = self.config.performance_thresholds

    -- 检查响应时间
    if perf.response_time.current > thresholds.response_time.critical then
        self:create_alert("critical", "response_time",
            string.format("响应时间严重超标: %.2f ms", perf.response_time.current))
    elseif perf.response_time.current > thresholds.response_time.warning then
        self:create_alert("warning", "response_time",
            string.format("响应时间超标: %.2f ms", perf.response_time.current))
    end

    -- 检查内存使用
    if perf.memory_usage.current > thresholds.memory_usage.critical then
        self:create_alert("critical", "memory_usage",
            string.format("内存使用严重超标: %.2f%%", perf.memory_usage.current))
    elseif perf.memory_usage.current > thresholds.memory_usage.warning then
        self:create_alert("warning", "memory_usage",
            string.format("内存使用超标: %.2f%%", perf.memory_usage.current))
    end

    -- 检查其他指标...
end

-- 创建告警
function PerformanceMonitor:create_alert(severity, metric, message)
    local current_time = os.time()

    -- 检查告警冷却时间
    local last_alert_time = self.state.last_alerts and self.state.last_alerts[metric] or 0
    if current_time - last_alert_time < self.config.alerting.alert_cooldown then
        return
    end

    local alert = {
        id = self:generate_alert_id(),
        severity = severity,
        metric = metric,
        message = message,
        timestamp = current_time,
        acknowledged = false,
        resolved = false
    }

    table.insert(self.state.alerts, alert)

    -- 记录最后告警时间
    self.state.last_alerts = self.state.last_alerts or {}
    self.state.last_alerts[metric] = current_time

    -- 发送告警
    self:send_alert(alert)

    Logger.warn("性能告警", alert)
end

-- 生成告警ID
function PerformanceMonitor:generate_alert_id()
    return string.format("alert_%d_%d", os.time(), math.random(1000, 9999))
end

-- 发送告警
function PerformanceMonitor:send_alert(alert)
    for _, channel in ipairs(self.config.alerting.alert_channels) do
        if channel == "console" then
            print(string.format("[%s] %s: %s",
                string.upper(alert.severity), alert.metric, alert.message))
        elseif channel == "file" then
            -- 写入日志文件
            Logger.error("性能告警: " .. alert.message, alert)
        elseif channel == "callback" then
            -- 调用回调函数
            if self.alert_callback then
                self.alert_callback(alert)
            end
        end
    end
end

-- 检查自动调优
function PerformanceMonitor:check_auto_tuning()
    if not self.config.auto_tuning.enabled then
        return
    end

    local current_time = os.time()

    -- 检查调优冷却时间
    if current_time - self.state.last_tuning_time < self.config.auto_tuning.tuning_cooldown then
        return
    end

    -- 检查是否需要调优
    local needs_tuning = self:evaluate_tuning_needs()

    if needs_tuning then
        self:execute_auto_tuning()
    end
end

-- 评估调优需求
function PerformanceMonitor:evaluate_tuning_needs()
    local perf = self.state.current_performance
    local thresholds = self.config.performance_thresholds

    -- 检查是否有严重性能问题
    if perf.response_time.current > thresholds.response_time.critical or
       perf.memory_usage.current > thresholds.memory_usage.critical or
       perf.cpu_usage.current > thresholds.cpu_usage.critical then
        return true
    end

    -- 检查是否有多个警告
    local warning_count = 0
    if perf.response_time.current > thresholds.response_time.warning then
        warning_count = warning_count + 1
    end
    if perf.memory_usage.current > thresholds.memory_usage.warning then
        warning_count = warning_count + 1
    end
    if perf.cpu_usage.current > thresholds.cpu_usage.warning then
        warning_count = warning_count + 1
    end

    -- 多个警告时触发调优
    return warning_count >= 2
end

-- 执行自动调优
function PerformanceMonitor:execute_auto_tuning()
    Logger.info("执行自动调优")

    local current_time = os.time()
    local tuning_results = {}

    -- 按优先级排序策略
    local sorted_strategies = {}
    for _, strategy in pairs(self.tuning_strategies) do
        table.insert(sorted_strategies, strategy)
    end

    table.sort(sorted_strategies, function(a, b)
        return a.priority < b.priority
    end)

    -- 执行适用的策略
    for _, strategy in ipairs(sorted_strategies) do
        if strategy.should_trigger(self.state.current_performance) then
            local result = strategy.execute(self.state.current_performance)

            table.insert(self.state.tuning_history, {
                timestamp = current_time,
                strategy = strategy.name,
                result = result,
                success = result.success
            })

            table.insert(tuning_results, {
                strategy = strategy.name,
                success = result.success,
                message = result.message
            })

            -- 如果是激进模式，继续执行其他策略
            if not self.config.auto_tuning.aggressive_mode then
                break
            end
        end
    end

    self.state.last_tuning_time = current_time

    Logger.info("自动调优完成", {
        strategies_executed = #tuning_results,
        results = tuning_results
    })
end

-- 更新健康分数
function PerformanceMonitor:update_health_score()
    local perf = self.state.current_performance
    local thresholds = self.config.performance_thresholds

    local scores = {}

    -- 计算各项指标的健康分数
    scores.response_time = self:calculate_health_score(
        perf.response_time.current,
        thresholds.response_time.warning,
        thresholds.response_time.critical
    )

    scores.memory_usage = self:calculate_health_score(
        perf.memory_usage.current,
        thresholds.memory_usage.warning,
        thresholds.memory_usage.critical
    )

    scores.cpu_usage = self:calculate_health_score(
        perf.cpu_usage.current,
        thresholds.cpu_usage.warning,
        thresholds.cpu_usage.critical
    )

    scores.error_rate = self:calculate_health_score(
        perf.error_rate.current * 100,
        thresholds.error_rate.warning * 100,
        thresholds.error_rate.critical * 100
    )

    scores.fps = self:calculate_health_score(
        perf.fps.current,
        thresholds.fps.warning,
        thresholds.fps.critical,
        true -- FPS越高越好
    )

    -- 计算综合健康分数
    local total_score = 0
    local count = 0
    for _, score in pairs(scores) do
        total_score = total_score + score
        count = count + 1
    end

    self.state.health_score = count > 0 and (total_score / count) or 1.0
end

-- 计算健康分数
function PerformanceMonitor:calculate_health_score(current, warning, critical, higher_is_better)
    higher_is_better = higher_is_better or false

    if higher_is_better then
        -- 对于FPS等指标，越高越好
        if current >= warning then
            return 1.0
        elseif current <= critical then
            return 0.0
        else
            return (current - critical) / (warning - critical)
        end
    else
        -- 对于响应时间等指标，越低越好
        if current <= warning then
            return 1.0
        elseif current >= critical then
            return 0.0
        else
            return 1.0 - (current - warning) / (critical - warning)
        end
    end
end

-- 生成性能报告
function PerformanceMonitor:generate_performance_report()
    local report = {
        timestamp = os.time(),
        health_score = self.state.health_score,
        current_performance = self.state.current_performance,
        alerts = self:get_active_alerts(),
        recent_tunings = self:get_recent_tunings(),
        recommendations = self:generate_recommendations()
    }

    return report
end

-- 获取活跃告警
function PerformanceMonitor:get_active_alerts()
    local active_alerts = {}
    local current_time = os.time()

    for _, alert in ipairs(self.state.alerts) do
        if not alert.resolved and (current_time - alert.timestamp) < 3600 then -- 1小时内的告警
            table.insert(active_alerts, alert)
        end
    end

    return active_alerts
end

-- 获取最近的调优记录
function PerformanceMonitor:get_recent_tunings()
    local recent_tunings = {}
    local current_time = os.time()

    for _, tuning in ipairs(self.state.tuning_history) do
        if (current_time - tuning.timestamp) < 3600 then -- 1小时内的调优
            table.insert(recent_tunings, tuning)
        end
    end

    return recent_tunings
end

-- 生成优化建议
function PerformanceMonitor:generate_recommendations()
    local recommendations = {}
    local perf = self.state.current_performance

    -- 响应时间建议
    if perf.response_time.current > 50 then
        table.insert(recommendations, {
            type = "response_time",
            priority = "high",
            message = "响应时间较高，建议优化算法或增加缓存"
        })
    end

    -- 内存使用建议
    if perf.memory_usage.current > 70 then
        table.insert(recommendations, {
            type = "memory_usage",
            priority = "medium",
            message = "内存使用率较高，建议优化数据结构或增加垃圾回收频率"
        })
    end

    -- CPU使用建议
    if perf.cpu_usage.current > 60 then
        table.insert(recommendations, {
            type = "cpu_usage",
            priority = "medium",
            message = "CPU使用率较高，建议优化计算密集型操作"
        })
    end

    -- AI性能建议
    if perf.ai_performance.decision_quality < 0.7 then
        table.insert(recommendations, {
            type = "ai_performance",
            priority = "low",
            message = "AI决策质量有提升空间，建议调整AI参数或训练模型"
        })
    end

    return recommendations
end

-- 获取性能数据
function PerformanceMonitor:get_performance_data()
    return {
        current = self.state.current_performance,
        history = self.state.performance_history,
        health_score = self.state.health_score,
        alerts = self.state.alerts,
        tuning_history = self.state.tuning_history
    }
end

-- 设置AI参数调优器
function PerformanceMonitor:set_ai_parameter_tuner(tuner)
    self.ai_parameter_tuner = tuner
    Logger.info("已设置AI参数调优器")
end

-- 设置告警回调
function PerformanceMonitor:set_alert_callback(callback)
    self.alert_callback = callback
    Logger.info("已设置告警回调函数")
end

-- 手动触发性能分析
function PerformanceMonitor:trigger_analysis()
    Logger.info("手动触发性能分析")

    self:collect_performance_metrics()
    self:analyze_performance()

    return self:generate_performance_report()
end

-- 重置监控数据
function PerformanceMonitor:reset_monitoring_data()
    Logger.info("重置监控数据")

    self.state.current_performance = self:initialize_performance_metrics()
    self.state.performance_history = {}
    self.state.alerts = {}
    self.state.tuning_history = {}
    self.state.health_score = 1.0

    -- 重置收集器
    self.collectors.error_rate.reset()
    self.collectors.fps.reset()
    self.collectors.ai_performance.reset()
end

-- 导出监控数据
function PerformanceMonitor:export_data()
    return {
        config = self.config,
        state = self.state,
        export_timestamp = os.time()
    }
end

-- 创建性能监控器实例
function PerformanceMonitor:new(config)
    local instance = {
        config = TableUtils.deep_copy(self.config),
        state = TableUtils.deep_copy(self.state),
        collectors = {},
        tuning_strategies = {}
    }

    setmetatable(instance, {__index = self})

    if config then
        TableUtils.merge(instance.config, config)
    end

    instance:init()

    return instance
end

return PerformanceMonitor